import React, { Component } from 'react'
import { Toast } from 'antd-mobile';
import SearchHeader from '../../components/SearchHeader'
import { WindowScroller, AutoSizer, List, InfiniteLoader } from 'react-virtualized';
import Sticky from '../../components/Sticky';
import HouseItem from "../../components/HouseItem"
import { BASE_URL } from '../../utils/url';
import styles from "./index.module.css"
import Filter from './components/Filter'
import { API } from "../../utils/api"

export default class SearchHouse extends Component {
    state = {
        citydata: JSON.parse(localStorage.getItem('hkzf_city')),
        list: [],
        count: 0,
        isLoading: false
    }
    // 初始化实例属性
    filters = {}
    componentDidMount() {
        this.searchHouseList()
    }
    // 获取房屋列表数据
    async searchHouseList() {
        // 获取当前城市
        const { value } = this.state.citydata
        this.setState({
            isLoading: true
        })
        Toast.loading('加载中...', 0, null, false)
        const res = await API.get('/houses', {
            params: {
                cityId: value,
                ...this.filters,
                start: 1,
                end: 20
            }
        })
        Toast.hide()
        const { list, count } = res.data.body
        this.setState({
            list,
            count,
            isLoading: false
        })
    }
    // 接受filter组件中的筛选条件
    onFilter = (filters) => {
        this.filters = filters
        // console.log(this.filters)
        // 调用获取房屋数据的方法
        this.searchHouseList()
    }
    //渲染list列表每一项
    renderHouseList = ({
        key, // 唯一KEY
        index, // 索引值
        style, // 重点属性，每一行数据都需要加上这个属性，指定每一行的位置 不加会有闪屏之类的问题
    }) => {
        // 返回值就是每一条dom层
        const { list } = this.state
        const house = list[index]
        // 判断有没house 没有就显示loading
        if (!house) {
            return <div key={key} style={style}>
                <p className={styles.loading}>加载中...</p>
            </div>
        }
        return (
            <HouseItem key={key} style={style} src={BASE_URL + house.houseImg} title={house.title} desc={house.desc} tags={house.tags} price={house.price} />
        );
    }
    //判断列表中每一行是否加载完成
    isRowLoaded = ({ index }) => {
        return !!this.state.list[index];
    }
    //获取更多房屋列表
    //注意该方法返回值是promise对象，这个对象应该在数据加载完成时，来调用resolve让promise对象的状态变为已完成
    loadMoreRows = ({ startIndex, stopIndex }) => {
        return new Promise(resolve => {
            //数据加载完成时调用resolve
            const { value } = this.state.citydata
            this.setState({
                isLoading: true
            })
            Toast.loading('加载中...', 0, null, false)
            API.get('/houses', {
                params: {
                    cityId: value,
                    ...this.filters,
                    start: startIndex,
                    end: stopIndex
                }
            }).then(res => {
                // console.log(res)
                this.setState({
                    list: [...this.state.list, ...res.data.body.list]
                })
                //加载完成调用resolve
                resolve()
            })
            Toast.hide()

            if (this.state.count !== 0) {
                Toast.info(`共找到${this.state.count}套房源`, 2, null, false)
            }
            this.setState({
                isLoading: false
            })
        })

    }
    render() {
        const { count, isLoading } = this.state
        return (
            <div className={styles.searchhouse}>
                <SearchHeader cityName={this.state.citydata.label} history={this.history} />
                <Sticky height={40}>
                    <Filter onFilter={this.onFilter} />
                </Sticky>
                {/* 房屋列表 */}
                {count === 0 && !isLoading ? <p className={styles.space}>没有合适房源，换个条件搜索一下吧~</p> : <div className={styles.house_list}>
                    <InfiniteLoader
                        isRowLoaded={this.isRowLoaded}
                        loadMoreRows={this.loadMoreRows}
                        minimumBatchSize={20}
                        rowCount={count}
                    >{({ onRowsRendered, registerChild }) => (
                        <WindowScroller>
                            {({
                                height, isScrolling, scrollTop
                            }) => (
                                <AutoSizer>
                                    {({ width }) => (
                                        <List
                                            autoHeight
                                            width={width}
                                            height={height}
                                            rowCount={count}//list列表总行数
                                            rowHeight={100}//每一行高度
                                            rowRenderer={this.renderHouseList}//渲染列表每一项
                                            isScrolling={isScrolling}
                                            scrollTop={scrollTop}
                                            onRowsRendered={onRowsRendered}
                                            ref={registerChild}
                                        />
                                    )}
                                </AutoSizer>
                            )}
                        </WindowScroller>
                    )}</InfiniteLoader>

                </div>}

            </div>
        )
    }
}
